from datetime import datetime
from django.views import View
from menu.models import SysRoleMenu
from role.models import SysRole, SysUserRole
from django.http import JsonResponse
import json
from django.core.paginator import Paginator
from role.serializer import SysRoleSerializer
# from role.models import SysUserRole


# Create your views here.
class ListAllView(View):
    def get(self, request):  # 查询一般用get请求
        obj_roleList = SysRole.objects.all().values()  # 化为字典
        roleList = list(obj_roleList)  # 化为列表
        return JsonResponse({"code": 200, "message": "查询成功", "roleList": roleList})


class SearchView(View):
    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        pageNum = data["pageNum"]
        pageSize = data["pageSize"]
        query = data["query"]  # 查询参数
        print(pageNum, pageSize)
        RoleListPage = Paginator(
            SysRole.objects.filter(name__icontains=query), pageSize
        ).page(pageNum)  # 分页,__icontains表示模糊查询
        obj_roles = RoleListPage.object_list.values()
        roles = list(obj_roles)
        total = SysRole.objects.filter(name__icontains=query).count()
        return JsonResponse({"code": 200, "roleList": roles, "total": total})


class SaveView(View):
    """
    添加修改
    """

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        if data["id"] == -1:
            obj_SysRole = SysRole(
                name=data["name"], code=data["code"], remark=data["remark"]
            )
            obj_SysRole.create_time = datetime.now().date
            obj_SysRole.save()
        else:
            obj_SysRole = SysRole(
                id=data["id"],
                name=data["name"],
                code=data["code"],
                remark=data["data"],
                create_time=data["create_time"],
                update_time=data["update_time"],
            )
            obj_SysRole.update_time = datetime.now().date
            obj_SysRole.save()
        return JsonResponse({"code": 200, "message": "保存成功"})


class ActionView(View):
    """
    根据ID获取角色信息
    """

    def get(self, request):
        id = request.GET.get("id")
        role_obj = SysRole.objects.get(id=id)
        return JsonResponse(
            {
                "code": 200,
                "message": "操作成功",
                "role": SysRoleSerializer(role_obj).data,
            }
        )

    def delete(self, request):
        idList = json.loads(request.body.decode("utf-8"))
        SysUserRole.objects.filter(role_id__in=idList).delete()
        SysRoleMenu.objects.filter(role_id__in=idList).delete()
        SysRole.objects.filter(id__in=idList).delete()
        return JsonResponse({"code": 200, "message": "删除成功"})

class MenusView(View):
    """
    根据角色ID获取菜单信息
    #这里的通俗易懂逻辑是,先根据角色ID获取角色菜单关系表中的所有菜单ID,然后将这些菜单ID提取出来放到一个列表中,最后返回给前端"""
    def get(self, request):
        id = request.GET.get("id")
        menuList = SysRoleMenu.objects.filter(role_id=id).values("menu_id") # 只获取menu_id字段
        menuIdList = [menu["menu_id"] for menu in menuList] # 提取menu_id列表
        print(menuIdList)
        # menuIdList = []
        # for menu in menuList:
        #     menuIdList.append(menu["menu_id"]) 这里不是很理解
        return JsonResponse({"code": 200, "message": "操作成功", "menuIdList": menuIdList})
        
class GrantView(View):
    """
    授权
    """
    def post(self, request):
        data = json.loads(request.body.decode("utf-8") )
        role_id = data["id"]
        menuIdList = data["menuIds"] # 前端传过来的菜单ID列表,用户选择最新的菜单ID列表
        print(role_id, menuIdList)
        # 先删除该角色ID对应的所有菜单ID
        SysRoleMenu.objects.filter(role_id=role_id).delete()
        for menuId in menuIdList:
            roleMenu = SysRoleMenu(role_id=role_id, menu_id=menuId) # 创建新的角色菜单关系对象
            roleMenu.save() # 保存到数据库     
        return JsonResponse({"code": 200, "message": "授权成功"})